package com.aaron.remoting.transport.netty.client;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// 维护一个缓存，从中去拿Channel
@Slf4j
public class ChannelProvider {

    /**
     * channelMap:
     *  key: InetSocketAddress.toString()
     *  value: Channel
     */
    private final Map<String, Channel> channelMap;

    public ChannelProvider() {
        channelMap = new ConcurrentHashMap<>();
    }

    // 从channelMap中获取Channel
    public Channel get(InetSocketAddress inetSocketAddress) {
        String key = inetSocketAddress.toString();
        if (channelMap.containsKey(key)) {
            Channel channel = channelMap.get(key);
            // 判断连接是否可用，Channel必须是active的
            if (channel != null && channel.isActive()) {
                return channel;
            } else {
                // 没有连接的channel应该移除出Map
                channelMap.remove(key);
            }
        }
        return null;
    }

    // 放入ChannelMap中,保存的是 key:ip地址 value:channel对象
    public void set(InetSocketAddress inetSocketAddress, Channel channel) {
        String key = inetSocketAddress.toString();
        channelMap.put(key, channel);
    }

    // 从ChannelMap中移除没有连接的channel
    public void remove(InetSocketAddress inetSocketAddress) {
        String key = inetSocketAddress.toString();
        channelMap.remove(key);
        log.info("Channel map size :[{}]", channelMap.size());
    }
}
